package com.zmn.plat.admin.controller.servcategory;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.DictModel;
import com.zmn.common.dto.VtDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.plat.admin.controller.PlatBaseController;
import com.zmn.plat.common.constant.BaseCodeMapConsts;
import com.zmn.plat.common.constant.OnePriceConsts;
import com.zmn.plat.common.util.StringToArrayUtil;
import com.zmn.plat.model.entity.base.fault.Fault;
import com.zmn.plat.model.entity.base.fault.FaultQuery;
import com.zmn.plat.model.entity.product.BaseCodeMap;
import com.zmn.plat.model.entity.product.BaseCodeMapQuery;
import com.zmn.plat.model.entity.servcategory.CategoryFaultImage;
import com.zmn.plat.model.entity.servcategory.CategoryFaultImageQuery;
import com.zmn.plat.model.entity.servcategory.ServAssCategory;
import com.zmn.plat.services.interfaces.base.fault.FaultService;
import com.zmn.plat.services.interfaces.product.BaseCodeMapService;
import com.zmn.plat.services.interfaces.servcategory.CategoryFaultImageService;
import com.zmn.plat.services.interfaces.servcategory.ServAssCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 后端产品分类-故障图片基础查询Controller
 *
 * @author yangshuangping
 * @since 2021/11/18 18:37
 */
@Slf4j
@RestController
@RequestMapping("/category/faultimage")
public class CategoryFaultImageListController extends PlatBaseController {

    @Resource
    private CategoryFaultImageService categoryFaultImageService;

    @Resource
    private ServAssCategoryService servAssCategoryService;

    @Resource
    protected FaultService faultService;

    @Resource
    protected BaseCodeMapService baseCodeMapService;

    /**
     * 描述: 查询列表
     *
     * @param query 查询实体
     * @return org.springframework.web.servlet.ModelAndView
     * @author yangshuangping
     * @since 2021/11/18 18:37
     */
    @RequestMapping("/list")
    public ModelAndView list(CategoryFaultImageQuery query) {

        if (NumberUtil.isNullOrZero(query.getGroupId())) {
            query.setGroupId(GlobalConsts.NONE);
        }
        ServAssCategory servAssCategory = servAssCategoryService.findByKey(query.getGroupId());
        List<CategoryFaultImage> items = categoryFaultImageService.listPageByQuery(query);
        ModelAndView mv = new ModelAndView("servasscategory/faultimage/list");
        convertChineseNames(items);
        mv.addObject("items", items);
        mv.addObject("vo", query);
        mv.addObject("servAssCategory", servAssCategory);
        mv.addObject("flag", 6);
        return mv;
    }

    /**
     * 描述: 详情
     *
     * @param faultId 主键id
     * @return org.springframework.web.servlet.ModelAndView
     * @author yangshuangping
     * @since 2021/11/18 18:37
     */
    @RequestMapping("/addEditView")
    public ModelAndView addEditView(@RequestParam(value = "faultId", defaultValue = "0") Integer faultId,
                                    @RequestParam(value = "groupId", defaultValue = "0") Integer groupId) {

        CategoryFaultImage categoryFaultImage;
        if (NumberUtil.isNullOrZero(faultId)) {
            categoryFaultImage = new CategoryFaultImage();
        } else {
            categoryFaultImage = categoryFaultImageService.findById(faultId);
        }

        ServAssCategory servAssCategory = Optional.ofNullable(servAssCategoryService.findByKey(groupId)).orElse(new ServAssCategory());

        List<VtDTO> list = new ArrayList<>();
        final List<Fault> listPFault = faultService.listByQuery(FaultQuery.builder().status(GlobalConsts.YES).build());
        list = listPFault.stream().map(x -> new VtDTO(x.getFaultId(), x.getFaultName() + "-" + x.getFaultId())).distinct().collect(Collectors.toList());
        List<VtDTO> pitchOn = new ArrayList<>();
        if (StringUtil.isNotBlank(categoryFaultImage.getFaultRelevance())) {
            List<Integer> ids = StringToArrayUtil.convertStrsToList(categoryFaultImage.getFaultRelevance());
            final List<Fault> faultList = faultService.listByIds(ids);
            if (CollectionUtil.isNotNullOrEmpty(faultList)) {
                pitchOn = faultList.stream().map(x -> new VtDTO(x.getFaultId(), x.getFaultName() + "-" + x.getFaultId())).collect(Collectors.toList());
            }
        }
        categoryFaultImage.setGroupId(groupId);
        ModelAndView mv = new ModelAndView("servasscategory/faultimage/detail");
        mv.addObject("categoryFaultImage", categoryFaultImage);
        mv.addObject("servAssCategory", servAssCategory);
        mv.addObject("listFault", list);
        mv.addObject("listPitchOnFault", pitchOn);
        mv.addObject("listFaultType", baseCodeMapFaultPart());
        return mv;
    }

    /**
     * 获取码表中故障部位
     *
     * @return
     */
    private List<DictModel> baseCodeMapFaultPart() {
        List<DictModel> list = new ArrayList<>();
        BaseCodeMapQuery query = new BaseCodeMapQuery();
        query.setOneTypeId(BaseCodeMapConsts.BASE_CODE_MAP_ONE_TYPE_NUMBER_FAULT_PART);
        query.setStatus(GlobalConsts.YES);
        List<BaseCodeMap> baseCodeMaps = baseCodeMapService.listByQuery(query);
        if (CollectionUtil.isNotNullOrEmpty(baseCodeMaps)) {
            list = baseCodeMaps.stream().map(x -> new DictModel(x.getThreeTypeId(), x.getName())).collect(Collectors.toList());
        }
        return list;
    }

    private void convertChineseNames(List<CategoryFaultImage> items) {
        Map<Integer, String> managesMap = Optional.of(baseCodeMapFaultPart().stream()
                        .collect(Collectors.toMap(DictModel::getKey, DictModel::getValue, (a, b) -> b)))
                .orElse(new HashMap<>());
        final List<Fault> listFault = faultService.listByQuery(new FaultQuery());

        if (CollectionUtil.isNotNullOrEmpty(items)) {
            for (CategoryFaultImage item : items) {
                item.setPartTypeName(managesMap.get(item.getPartType()));
                if (StringUtil.isNotBlank(item.getFaultRelevance())) {
                    List<Integer> faultIds = StringUtil.convertStrsToList(item.getFaultRelevance());
                    List<String> list = listFault.stream()
                            .filter(x -> faultIds.contains(x.getFaultId()))
                            .map(x -> String.format("%s%s%d", x.getFaultName(), OnePriceConsts.SPLITER_STRIPING, x.getFaultId()))
                            .distinct()
                            .collect(Collectors.toList());
                    item.setFaultRelevance(list.stream().collect(Collectors.joining(",")));
                }
            }
        }
    }

}
